﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;

namespace Jian.Vubackup.MySql
{
    public class ConfigManager
    {
        private IConfiguration config;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="filename">指定的配置文件</param>
        public ConfigManager(string filename)
        {
            config = new ConfigurationBuilder()
                .AddInMemoryCollection()//将配置文件的数据加载到内存中
                .SetBasePath(AppContext.BaseDirectory)//指定配置文件所在的目录
                .AddJsonFile(filename, optional: true, reloadOnChange: true)  //指定加载的配置文件
                .Build();
        }

        public T GetConfig<T>(string key) where T : class, new()
        {

            var appconfig = new ServiceCollection()
            .AddOptions()
            .Configure<T>(config.GetSection(key))
            .BuildServiceProvider()
            .GetService<IOptions<T>>()
            .Value;

            return appconfig;
        }
    }
}
